package com.tgu.service.impl;

import com.tgu.entity.model.CommentEntity;
import com.tgu.entity.model.OrdersEntity;
import com.tgu.mapper.CommentDao;
import com.tgu.mapper.OrdersDao;
import com.tgu.mapper.UsersDao;
import com.tgu.service.ICommentService;
import com.tgu.utils.result.Result;
import com.tgu.utils.result.SystemCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CommentServiceImpl implements ICommentService {

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private UsersDao usersDao;

    @Autowired
    private OrdersDao ordersDao;

    @Override
    @Transactional
    public Result insertComment(CommentEntity comment) {
        if (comment == null) {
            return Result.error(SystemCodeEnum.DATA_ERROR);
        }
        if (usersDao.selectById(comment.getUserId()) == null) {
            return Result.error(SystemCodeEnum.USER_NOT_EXIST);
        }
        OrdersEntity order = ordersDao.selectById(comment.getOrderId());
        if (order == null) {
            return Result.error(SystemCodeEnum.ORDER_NOT_EXIST);
        }
        order.setCommented(1);
        ordersDao.updateById(order);

        int insert = commentDao.insert(comment);
        if (insert == 0) {
            return Result.error(SystemCodeEnum.INSERT_COMMENT_ERROR);
        }

        return Result.ok(SystemCodeEnum.COMMENT_SUCCESS);
    }
}
